var ballr = 10;

function draw() {
    clear();
    ctx.drawImage(backgroundImages[backgroundImage], 0, 0);
    ctx.drawImage(ball, x, y);

    $('#level').html("Level " + level);
    
    if (rightDown) {
	paddlex += 5;
    } else if (leftDown) {
	paddlex -= 5;
    }

    ctx.drawImage(paddle, paddlex, HEIGHT - paddleh, paddlew, paddleh);
    
    drawbricks();
    drawLives();
    drawPowerUp();
    ctx.font = "bold 24px sans-serif";
    ctx.fillStyle = "white";
    ctx.fillText(score, 500, 30);
    
    rowheight = BRICKHEIGHT + PADDING;
    colwidth = BRICKWIDTH + PADDING;
    row = Math.floor(y / rowheight);
    col = Math.floor(x / colwidth);

    if (y < numrows * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
    	dy = -dy;
    	bricks[row][col] = 0;
    	score += 5;
	destroyEffect.play();
    	if (brickPowerUps[row] && brickPowerUps[row][col] == 1) {
    	    throwPowerUp();
    	}
    	if (isZeroesArray(bricks)) {
    	    nextLevel();
    	}
    }

    if (x + dx + ballr > WIDTH || x + dx - ballr < 0) {
	xBounceEffect.play();
	dx = -dx;
    }
    
    if (y + dy - ballr < 0) {
	yBounceEffect.play();
	dy = -dy;
    } else if (y + dy + ballr > HEIGHT - paddleh) {
	if (x > paddlex && x < paddlex + paddlew) {
	    dx = 8 * ((x-(paddlex+paddlew/2))/paddlew);
	    dy = -dy;
	    hitEffect.play();
	}
	else if (y + dy + ballr > HEIGHT) {
	    lives -= 1;
	    if (lives > 0) {
		restart();
	    } else {
		gameOver();
	    }
	}
    }

    if (powerUpX > paddlex && powerUpX < paddlex + paddlew
	&& powerUpY > HEIGHT - paddleh) {
	catchPowerUp();
    }
	if (powerUpY > HEIGHT + 20) {
		missPowerUp();
	}

    x += dx;
    y += dy;
}
